var currentAdress = ""
var cityId
var shopTypeId
var currentLat    //当前纬度
var currentLng    //当前经度
var userId = 0
var getRequest = GetRequest();
var code = getRequest.code;
var infrom = getRequest.infrom;
var cityName;

if (infrom == "1") {
    //授权跳转
    checkAuthUser(code)
} else {
    userId = GetQueryString('userId')
    if (!userId) {
        alert("网络走丢了")
        window.history.back(-1);
    }
}

$(function () {
    //初始化页面
    queryIndexInfo()
    getMenu();
    selectIndexCarouselList()   //填充轮播
    selectShopTypeList()    //填充店铺分类
    selectCityList()        //填充城市列表
    /*获取用户当前地址*/
    var map = new BMap.Map("allmap");
    var geolocation = new BMap.Geolocation();
    geolocation.getCurrentPosition(function (r) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
            currentLat = r.point.lat;   //纬度
            currentLng = r.point.lng;  //经度

            var gc = new BMap.Geocoder();
            gc.getLocation(r.point, function (rs) {
                //获取当前点击 位置的 省市县，街道号 和街道名称。并显示在 文本框中
                //街道号 和街道名称 不1定能获取到，有时候为空。
                var addComp = rs.addressComponents;
                var province = addComp.province;
                cityName = addComp.city;
                var district = addComp.district;
                var street = addComp.street;
                var streetNumber = addComp.streetNumber;
                var adress = province + cityName + district + street + streetNumber
                currentAdress = adress
                $('.currentCity').text(cityName)
                queryAdvList(cityName)  //查询广告位商铺以及显示距离
            })

        } else {
            alert('failed' + this.getStatus());
        }
    }, {enableHighAccuracy: true});

})

//授权校验用户授权
function checkAuthUser(code) {
    if (code != null) {//有code
        var data = {};
        //后台获取access_token接口
        var url = getWeiContextPath() + "/wx/VipUser/GetToken";
        data.code = code;//课程
        //同步ajax,供方法中调接口
        $.ajax({
            type: "POST",
            cache: false,
            data: data,
            async: false,
            url: url,
            success: function (result) {
                if (result.data) {    //已经是会员
                    userId = result.data.id
                }
            },
            error: function (result) {
                alert("网络走丢了")
            }
        });
    } else {
        //没有code,再次请求获取code
        var pageUrl = window.location.href
            .replace(/[/]/g, "%2f")
            .replace(/[:]/g, "%3a")
            .replace(/[#]/g, "%23")
            .replace(/[&]/g, "%26")
            .replace(/[=]/g, "%3d");
        var url =
            "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
            getWeixinConfig().APPID +
            "&redirect_uri=" +
            pageUrl +
            "&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect";
        window.location.href = url;
    }
}

//页面初始加载
function queryIndexInfo() {
    /*隐藏右上角菜单*/
    document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {
        // 通过下面这个API隐藏右上角按钮
        WeixinJSBridge.call('hideOptionMenu');
    });
    //城市切换
    $('#js_city').on('click', function () {
        $('.geographical').show();
        $('.content_box').hide();

        /* window.location.href = "cityList.html"*/
    })
    $('#js_shop').on('click', function () {
        $('.geographical').hide();
        $('.content_box').show();
    })


}

/*轮播展示*/
function selectIndexCarouselList() {
    $.get(getWeiContextPath() + "/wx/data/queryNowList", function (res) {
        console.log(res)
        var _carouselList = $('#carouselList').empty()
        $.each(res, function (i, obj) {
            if (obj.reserve == 0) {   //跳转商铺
                _carouselList.append('<li>\n' +
                    '                    <a  href="store.html?shopId=' + obj.shopId + '&userId='+userId+'">\n' +
                    '                        <img src="' + getImgSrc(obj.imgUrl) + '" alt="">\n' +
                    '                    </a>\n' +
                    '                </li>')
            } else {    //跳转外网
                _carouselList.append('<li>\n' +
                    '                    <a href="' + obj.seatId + '">\n' +
                    '                        <img src="' + getImgSrc(obj.imgUrl) + '" alt="">\n' +
                    '                    </a>\n' +
                    '                </li>')
            }

        })

        // <!--中部自动轮播广告-->
        $('#slide2').swipeSlide({
            autoSwipe: true, //自动切换默认是
            speed: 3000, //速度默认4000
            continuousScroll: true, //默认否
            transitionType: 'cubic-bezier(0.22, 0.69, 0.72, 0.88)', //过渡动画linear/ease/ease-in/ease-out/ease-in-out/cubic-bezier
            lazyLoad: true, //懒加载默认否
        });

    })
}

/*商铺类型展示*/
function selectShopTypeList() {
    $.get(getWeiContextPath() + "/wx/data/selectShopTypeList", function (res) {
        console.log(res)
        var liLength = Math.ceil(res.length / 10);
        var _shopTypeList = $('#shopTypeList').empty()
        var _swiperList = $('#swiperList').empty()
        for (i = 0; i < liLength; i++) {
            _shopTypeList.append('<li/>')
            _swiperList.append('<span/>')
        }
        $.each(res, function (i, obj) {
            var index = Math.floor(i / 10)
            _shopTypeList.find('li').eq(index).append('<div class="weui_grid_box" onclick="searchShopList(' + obj.id + ')">\n' +
                '                        <div class="weui_grid_icon">\n' +
                '                            <img src="' + getImgSrc(obj.imgUrl) + '" alt="">\n' +
                '                        </div>\n' +
                '                        <p class="weui_grid_label">\n' + obj.typeName +
                '                        </p>\n' +
                '                    </div')
        })
        _swiperList.children().first().addClass('swiper_active')   //分页滑块

        //头部分类手动轮播
        $('#slide3').swipeSlide({
            autoSwipe: false, //自动切换默认是
            speed: 3000, //速度默认4000
            continuousScroll: false, //默认否
            transitionType: 'cubic-bezier(0.22, 0.69, 0.72, 0.88)', //过渡动画linear/ease/ease-in/ease-out/ease-in-out/cubic-bezier
            lazyLoad: true, //懒加载默认否
            callback: function (e) {
                $('.swiper_paging span').removeClass('swiper_active').eq(e).addClass('swiper_active');
            }
        });

    })
}

/*城市展示*/
function selectCityList() {
    $.get(getWeiContextPath() + "/wx/data/selectCityList", function (res) {

        var hashMap={}
        $.each(res, function (i, obj) {
            if(hashMap[obj.parentId]){
                hashMap[obj.parentId].push(obj)
            }else{
                hashMap[obj.parentId]=[obj];
            }
        })
        function digui(item){
            var arr=['<a class="weui-cell weui-cell_access" href="javascript:;"><div class="weui-cell__bd"><p>'+item.cityName+'</p></div><div class="weui-cell__ft"></div></a>']
            if(hashMap[item.cityId]!=undefined)
            {
                arr.push('<ul>')
                $.each(hashMap[item.cityId],function (j,obj) {
                    arr.push('<li cityId="' + obj.cityId + '" >' +digui(obj) + '</li>')
                })
                arr.push("</ul>")
            }
            return  arr.join('');
        }
        var htmlAry=[]
        $.each(hashMap['100'],function (i,item) {
            htmlAry.push('<li cityId="' + item.cityId + '" >' + digui(item) + '</li>')
        });
        $('.city_list').append(htmlAry.join(""))
        $('.city_list').on('click', 'li',function (e) {
            var city = $(this).text();
            cityId = $(this).attr("cityId")
            var _ul=$(this).children("ul");
            if(_ul.length){
                _ul.slideToggle()
            }else{
                searchListByCityId(cityId);
                $('.current_city label').text(city);
                $('#js_city span').text(city);
                $('.geographical').hide();
                $('.content_box').show();
            }
            e.stopPropagation()
        })
    })
}
/*商铺展示*/
function queryAdvList(cityName) {
    var data = {}
    data.currentLat = currentLat
    data.currentLng = currentLng
    data.pageNum = pageNum
    data.pageSize = pageSize
    if (cityId) {
        data.cityId = cityId
    }else {
        data.cityName = cityName
    }
    if (shopTypeId) {
        data.shopTypeId = shopTypeId
    }
    $.post(getWeiContextPath() + "/wx/adv/searchShopList", data, function (res) {
        var _shopList = $('#shopList')
        if (res.list.rows.length > 0) {
            $.each(res.list.rows, function (i, obj) {
                var rjf = 1 * obj.discountRatio * res.returnRatio * 10;
                _shopList.append(' <li class="shop_li">\n' +
                    '                    <a href="store.html?shopId=' + obj.shopId + '&userId='+userId+'">\n' +
                    '                      <div class="shop_img"><img src="' + getImgSrc(obj.imgUrls) + '" alt="'+obj.shopName+'" class="shop_img">\n' +
                    '                        </div><div class="shop_info">\n' +
                    '                            <p class="shop_title">' + obj.shopName + '</p>\n' +
                    '                            <p class="shop_youhui">每消费1元获得' + rjf.toFixed(2) + '积分</p>\n' +
                    '                            <p class="shop_address">' + (obj.distancenum / 1000) + 'km</p>\n' +
                    '                        </div>\n' +
                    '                    </a>\n' +
                    '                </li>')
            })
        } else {
            loading = true;
        }
        $(".weui-loadmore").hide();
    })
}
/*分类切换*/
function searchShopList(sId) {
    loading = false
    pageNum = 1;
    shopTypeId = sId
    $('#shopList').empty()
    queryAdvList()
}
/*城市切换*/
function searchListByCityId(cid) {
    loading = false
    pageNum = 1;
    cityId = cid
    $('#shopList').empty()
    queryAdvList()
}


function getMenu() {
    $('.weui-tabbar').html('<a href="javascript:void (0)" class="weui-tabbar__item weui-bar__item--on">\n' +
        '                <div class="weui-tabbar__icon">\n' +
        '                    <img src="images/shouye1.png" alt="">\n' +
        '                </div>\n' +
        '                <p class="weui-tabbar__label">首页</p>\n' +
        '            </a>\n' +
        '            <a href="discover.html?userId=' + userId + '" class="weui-tabbar__item">\n' +
        '                <div class="weui-tabbar__icon">\n' +
        '                    <img src="images/faxianguanli.png" alt="">\n' +
        '                </div>\n' +
        '                <p class="weui-tabbar__label">发现</p>\n' +
        '            </a>\n' +
        '            <a href="cellect.html?userId=' + userId + '" class="weui-tabbar__item">\n' +
        '                <div class="weui-tabbar__icon">\n' +
        '                    <img src="images/order.png" alt="">\n' +
        '                </div>\n' +
        '                <p class="weui-tabbar__label">收藏</p>\n' +
        '            </a>\n' +
        '            <a href="me.html?userId=' + userId + '" class="weui-tabbar__item">\n' +
        '                <div class="weui-tabbar__icon">\n' +
        '                    <img src="images/me.png" alt="">\n' +
        '                </div>\n' +
        '                <p class="weui-tabbar__label">我的</p>\n' +
        '            </a>')
}

var loading = false;  //状态标记
var pageNum = 1;
var pageSize = 4
$(document.body).infinite().on("infinite", function () {
    if (loading) return;
    loading = true;
    pageNum++; //页数
    $('.weui-loadmore').show();
    setTimeout(function () {
        queryAdvList(cityName)
        loading = false;
    }, 1500);   //模拟延迟
});

/*去搜索页面*/
function toSearch() {
    window.location.href = "search.html?userId="+userId
}
/*去我的页面*/
function toMe() {
    window.location.href = "me.html?userId="+userId
}





